home *** CD-ROM | disk | FTP | other *** search
/ Night Owl 6 / Night Owl's Shareware - PDSI-006 - Night Owl Corp (1990).iso / 033a / cwexp104.zip / GETOPT.C < prev   
C/C++ Source or Header  |  1991-09-21  |  2KB  |  72 lines

  1. /*
  2.  * getopt.c - Taken off net.sources from Henry Spencer.  It is a public 
  3.  *   domain getopt(3) like in System V.  It has been modified slightly,
  4.  *   including making it look a little more ANSI-ish.
  5. */
  6. #include <stdio.h>
  7.  
  8. #define   ARGCH    (int)':'
  9. #define   BADCH    (int)'?'
  10. #define   EMSG     ""
  11.  
  12. /* this is included because index is not on some UNIX systems 
  13. */
  14. static char  *index (register char *s, register int c)
  15. {
  16.    while (*s)
  17.       if (c == *s) return (s);
  18.       else s++;
  19.    return (NULL);
  20. }
  21.  
  22. /*
  23.  * get option letter from argument vector
  24.  */
  25. int  opterr = 1,    /* useless, never set or used */
  26.      optind = 1,    /* index into parent argv vector */
  27.      optopt;        /* character checked for validity */
  28. char *optarg;        /* argument associated with option */
  29.  
  30. /* eject  */
  31.  
  32. int getopt(int nargc, char **nargv, char *ostr)
  33. {
  34.    static char *place = EMSG;    /* option letter processing */
  35.    register char *oli;        /* option letter list index */
  36.    char   *index(char *s, int c);
  37.  
  38.    if ( !*place ) {        /* update scanning pointer */
  39.       if ( optind >= nargc || *(place = nargv[optind]) != '-' || !*++place ) 
  40.      return(EOF);
  41.       if ( *place == '-' ) {    /* found "--" */
  42.          ++optind;
  43.          return(EOF);
  44.       }
  45.    }    /* option letter okay? */
  46.    if ( (optopt = (int)*place++) == ARGCH || !(oli = index(ostr,optopt)) ) {
  47.       if ( !*place ) 
  48.          ++optind;
  49.       return(BADCH);
  50.       
  51.    }
  52.    if ( *++oli != ARGCH ) {    /* don't need argument */
  53.       optarg = NULL;
  54.       if ( !*place ) 
  55.      ++optind;
  56.    }
  57.    else {            /* need an argument */
  58.       if ( *place ) 
  59.      optarg = place;    /* no white space */
  60.       else 
  61.      if (nargc <= ++optind) {    /* no arg */
  62.             place = EMSG;
  63.         return(BADCH);
  64.          }
  65.          else optarg = nargv[optind];    /* white space */
  66.             place = EMSG;
  67.       ++optind;
  68.    }
  69.    return(optopt);         /* dump back option letter */
  70. }
  71.  
  72.